﻿using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace Demo.OData
{
  public partial class ProductFormODATA : System.Windows.Controls.DGTB.DataFormWindow
  {
    public ProductFormODATA()
    {
      InitializeComponent();
      CancelButton.Click += new RoutedEventHandler(CancelButton_Click);
      OKButton.Click += new RoutedEventHandler(OKButton_Click);
    }
    override public bool ValidateItem()
    {
      return !coErrorSummary.HasErrors;
    }

    public override void CancelEdit()
    {
      if(CurrentItem is IEditableObject) ((IEditableObject)CurrentItem).CancelEdit();
    }

    override public object CreateNewItem()
    {
      var ds = this.ItemsSource as Slma.OData.ODataSourceView;

      var data = ds.CreateEntity();
      data.SetValue("ProductID",Guid.NewGuid());
      data.SetValue("SellStartDate", DateTime.Now.Date);
      data.ValidatePropertyValue = true;
      return data;
    }

    public override void EditItem(object item, Action<bool> callback)
    {
      if(item is IEditableObject) ((IEditableObject)item).BeginEdit();
      callback(true);
    }

    public override void SubmitChanges(bool isNewItem, Action<bool> callback)
    {
      if(CurrentItem is IEditableObject) ((IEditableObject)CurrentItem).EndEdit();
      if(isNewItem) ((Slma.OData.ODataSourceView)ItemsSource).Add(CurrentItem);
      callback(true);
    }

    void OKButton_Click(object sender, RoutedEventArgs e)
    {
      CommitEditAndCloseWindow();
    }

    void CancelButton_Click(object sender, RoutedEventArgs e)
    {

      CancelEditAndCloseWindow();
    }
  }
}
